iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 24
0

正常寫一個範例

import React, {useState} from 'react';


const Test1 = () => {
  console.log('Test1')

  return(
      <div>Test1</div>
  );
}


export default function App() {

  const [count, setCount] = useState(0);

  return (
    <div>
          <Test1 />
          <button onClick={(e) => { setCount( count+1 ) }}>ADD</button>
          <p>count:{count}</p>

    </div>
  )
}

點擊ADD 會發現console.log會一直被觸發。
https://ithelp.ithome.com.tw/upload/images/20200924/201102923IcSBTUMiH.png

加入memo 後

import React, {useState} from 'react';


const Test1 = (props) => {
  console.log('Test1')

  return(
      <div>Test1</div>
  );
}

const Test2 = React.memo(Test1);
export default function App(props) {

  const [count, setCount] = useState(0);

  return (
    <div>
          <Test2 />
          <p>count:{count}</p>
          <button onClick={(e) => { setCount( count+1 ) }}>ADD</button>
    </div>
  )
}

https://ithelp.ithome.com.tw/upload/images/20200924/20110292ob2PEt61HV.png

const MyComponent = React.memo(function MyComponent(props) {
  /* render using props */
});

官方文件
React.memo is a higher order component.

If your component renders the same result given the same props, you can wrap it in a call to React.memo for a performance boost in some cases by memoizing the result. This means that React will skip rendering the component, and reuse the last rendered result.

React.memo only checks for prop changes. If your function component wrapped in React.memo has a useState or useContext Hook in its implementation, it will still rerender when state or context change.

By default it will only shallowly compare complex objects in the props object. If you want control over the comparison, you can also provide a custom comparison function as the second argument.

他說memo是一個進階的語法,memo是透過記憶的方式將效能優化
memo 是一個很好用的語法,但它不能用在class裡面,只能用在函數組件


上一篇
day 23 嘗試用目前學到的寫一個useHover
下一篇
day 25 useMemo 說明 與 組件傳值
系列文
react.js 的學習筆記 (沒在用硬要學30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言